#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json

from bottle import Bottle
from bottle import request, response

from excel.EGI.EgiDictUtil import EgiDictUtil

EgiAdm = Bottle()


@EgiAdm.hook('before_request')
def validate():
    REQUEST_METHOD = request.environ.get('REQUEST_METHOD')
    HTTP_ACCESS_CONTROL_REQUEST_METHOD = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
    if REQUEST_METHOD == 'OPTIONS' and HTTP_ACCESS_CONTROL_REQUEST_METHOD:
        request.environ['REQUEST_METHOD'] = HTTP_ACCESS_CONTROL_REQUEST_METHOD


@EgiAdm.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'  # 允许所有域名的请求
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, PUT, HEAD, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'origin,content-type,accept,authorization,x-requested-with'
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers['Access-Control-Max-Age'] = 86400
    response.status = 200


# Excel自研数据演算服务
# Vue+ele管理台界面数据接口

class EgiAdminRoute:
    TEST_SELECT_PAYMENT = 10
    TEST_SELECT_ANB = 7
    TEST_SUM_ASSURED = 1000000
    TEST_GENDER = "M"
    TEST_SMOKER = "N"
    TEST_REPEAT_PLAN = 1
    TEST_REPEAT_GROWTH_RATE = float(1 / 100)
    TEST_CURRENCY = "HKD-U"
    TEST_PROMOTION = "Y"
    TEST_WITHDRAWAL_STARTING_ANB = 66
    TEST_SURRENDER_ANB = 91
    TEST_WITHDRAWAL_YEARS = 0
    TEST_INFLATION = 0
    TEST_FST_YEAR_WITHDRAWAL = 0

    TEST_YEAR = range(101)

    json_data_file = ""
    ERROR_CODE = {
        "80": "数据读取异常错误，请联系管理员",
        "99": "处理参数错误",
        "100": "数据添加失败，请检查服务端日志",
        "102": "数据更新失败，请检查服务端日志",
        "103": "数据删除失败，请检查服务端日志",
        "104": "数据停止失败，请检查服务端日志",
        "105": "数据恢复失败，请检查服务端日志",
        "106": "数据激活失败，请检查服务端日志",
        "109": "数据不存在，数据处理失败",
    }

    impl = None

    def __init__(self, service):
        EgiAdminRoute.impl = service
        return

    @staticmethod
    @EgiAdm.post('/initKeyParam')
    def init_cal_param():
        # select_payment = request.forms.
        if request.json is not None:
            select_year = request.json['year']  # year 计算年期
            select_payment = request.json['select_payment']  # Payment Term 供款期
            select_anb = request.json['select_anb']  # ANB 翌年歲
            currency = request.json['currency']  # Currency 貨幣
            currency = currency.replace("_", "-")
            irr_anb = request.json['irr_anb']  # IRR 翌年歲
            cash_payment_irr = request.json['cash_payment_irr']  # 現金提取 IRR
            accumulation_irr = request.json['accumulation_irr']  # 積存 IRR
            saving = request.json['saving']  # 儲蓄金額
            repeat_saving_plan = request.json['repeat_saving_plan']  # 重複儲蓄計劃
            repeat_saving_growth_rate = request.json['repeat_saving_growth_rate']  # 重複儲蓄增長率
            promotion = request.json['promotion']
            if select_anb == None:
                return {'code': EgiAdminRoute.ERROR_CODE["99"], 'data': None, 'message': '次年歲'}
            if not promotion is None:
                promotion = 'Y' if promotion else 'N'
            str_res = EgiDictUtil.make_json_key(payment_term=select_payment, anb=select_anb,
                                                currency=currency, irr_anb=irr_anb, cash_payment_irr=cash_payment_irr,
                                                saving=saving, accumulation_irr=accumulation_irr, promotion=promotion,
                                                repeat_saving_plan=repeat_saving_plan,
                                                repeat_saving_growth_rate=repeat_saving_growth_rate, )
            str_res = "EGI-" + str_res
            hitnnt = EgiAdminRoute.impl.do_chck_key_exist(str_res)
            obj_data = None
            if hitnnt['code'] == 200:
                if hitnnt['data']:
                    obj_data = {"key": str_res, "hit": hitnnt, "res_msg": "中签"}
                else:
                    obj_data = {"key": str_res, "hit": hitnnt, "res_msg": "未中签"}
            else:
                return {'code': 99, 'data': obj_data, 'message': EgiAdminRoute.ERROR_CODE["99"]}
            return {'code': 200, 'data': obj_data, 'message': ""}

    @staticmethod
    @EgiAdm.get('/initStdBaseTab')
    def cal_purnm():
        strPram = request.params.strPram
        select_year = request.params.year  # year 计算年期
        if strPram is None or len(strPram) == 0:
            return {'code': 99, 'data': None, 'message': EgiAdminRoute.ERROR_CODE["99"]},
        res = EgiAdminRoute.impl.do_std_base_tab(str_param=strPram, years=range(int(select_year) + 1))
        if res["code"] != 200:
            return {'code': 99, 'data': None, 'message': EgiAdminRoute.ERROR_CODE["99"]}
        view_list = json.loads(res['data'])
        return {'code': 200, 'data': view_list, 'message': ""}
